package com.hyt.it.ogt.ks.mq;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

import javax.annotation.Resource;

import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.hyt.it.ogt.ks.model.vo.InitCandidateDataVO;
import com.hyt.it.ogt.ks.service.InitCandidateDataService;
import com.rabbitmq.client.Channel;

import lombok.extern.slf4j.Slf4j;

/**
 * @author wuyingge
 * @ClassName InitCandidateDataConsumer.java
 * @Description 手动触发考试-考生试卷初始化消息者
 * @createTime 2021年09月17日 17:42:00
 */
@Component
@Slf4j
public class InitCandidateDataConsumer {

    @Resource
    private InitCandidateDataService initCandidateDataService;
    @Resource
    private RedisTemplate redisTemplate;

    @RabbitListener(bindings = {@QueueBinding(value = @Queue( value = "${mq.initCandidateData.ksQueue}",
            autoDelete = "false",durable = "true"),
            exchange = @Exchange( value = "${mq.ksDirect}" ,type = ExchangeTypes.DIRECT),
            key = {"${mq.initCandidateData.ksRoute}"})})
    public void InitCandidateDataMessage(String json, Message message, Channel channel){
        try {
            log.info("初始化考生试题MQ监听消息内容:【{}】", json);
            List<InitCandidateDataVO> datas = JSON.parseObject(json,new TypeReference<List<InitCandidateDataVO>>(){});
            Integer type = datas.get(0).getType();
            if(Objects.equals(type,1)){
                initCandidateDataService.consumer(datas);
                return;
            }
            if(Objects.equals(2,type)){
                initCandidateDataService.consumerClearData(datas.get(0).getExamId());
            }
            if(Objects.equals(3,type)){
                InitCandidateDataVO job = datas.get(0);
                initCandidateDataService.clearCandidateInitData(job.getCpsMap(),job.getCandidateIds(),job.getExamId());
            }
        } catch (Exception e) {
            log.error("初始化考生试题MQ异常: 【{}】------{}", json, e);
        } finally {
            try {
                // 确认消费一条消息
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } catch (IOException e) {
                log.error("初始化考生试题消息异常: 【{}】------{}", json, e);
            }
        }
    }
}
